import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    list: [],
    inputValue: 'aaa',
    nextId: 5,
    keyView: 'all'
  },
  mutations: {
    // 设置list
    initList (state, data) {
      state.list = data
    },
    // 用户输入input值
    setInputValue (state, value) {
      state.inputValue = value
    },
    // 增加
    addItem (state) {
      var obj = {
        id: state.nextId,
        info: state.inputValue,
        done: false
      }
      state.list.push(obj)
      state.nextId++
      state.inputValue = ''
    },
    // 删除
    removeItem (state, id) {
      var i = state.list.findIndex(item => item.id === id)
      if (i !== -1) {
        state.list.splice(i, 1)
      }
    },
    // 修改done状态
    statusChange (state, param) {
      var i = state.list.findIndex(item => item.id === param.id)
      if (i !== -1) {
        state.list[i].done = param.done
      }
    },
    // 清除已完成
    clean (state) {
      state.list = state.list.filter(item => item.done === false)
    },
    // 切换全部、已完成、未完成
    changeListView (state, key) {
      state.keyView = key
    }
  },
  actions: {
    getList (context) {
      axios.get('/data.json').then(({ data }) => {
        context.commit('initList', data)
      })
    }
  },
  getters: {
    unDoneList: function (state) {
      return state.list.filter(item => item.done === false).length
    },
    infoList: function (state) {
      if (state.keyView === 'all') {
        return state.list
      } else if (state.keyView === 'undone') {
        return state.list.filter(item => item.done === false)
      } else if (state.keyView === 'done') {
        return state.list.filter(item => item.done === true)
      } else {
        return state.list
      }
    }
  }
})
